#include <os/ipc.h>
#define NUM_MAX_BARRIER 16

barrier_t barrier_table[NUM_MAX_BARRIER]={{
	.inuse = NOTUSING,
	.key = 42356,
}};

int do_barrier_init(int key,unsigned count){
	int i=0;
	for(i=0;i<NUM_MAX_BARRIER;i++){
		if(barrier_table[i].inuse == NOTUSING)
			break;
	}
	barrier_table[i].key=key;
	barrier_table[i].count=count;
	barrier_table[i].num_waiting=0;
	barrier_table[i].inuse=USING;
	queue_init(&(barrier_table[i].block_queue));
	return i;
}
extern int screen_cursor_x;
extern int screen_cursor_y;
int do_barrier_wait(int key){
	int i=0;
	for(i=0;i<NUM_MAX_BARRIER;i++)
		if(barrier_table[i].key==key && barrier_table[i].inuse== USING)
			break;
	if(i==NUM_MAX_BARRIER)
		return 0;
	barrier_table[i].num_waiting++;
	/*vt100_move_cursor(1,5);
	screen_cursor_x=1;
	screen_cursor_y=5;
	prints("> [BARRIER] (%d) processes in barrier,pid(%d)\n",barrier_table[i].num_waiting,do_getpid());
	vt100_move_cursor(current_running->cursor_x,current_running->cursor_y);
	screen_cursor_x=current_running->cursor_x;
	screen_cursor_y=current_running->cursor_y;*/
	if(barrier_table[i].count == barrier_table[i].num_waiting){
		while(!queue_is_empty(&(barrier_table[i].block_queue)))
			do_unblock(&(barrier_table[i].block_queue));
		barrier_table[i].num_waiting=0;
	}else
		do_block(&(barrier_table[i].block_queue));
	return 1;
}

int do_barrier_destroy(int id){
	barrier_table[id].inuse = NOTUSING;
	while(!queue_is_empty(&(barrier_table[id].block_queue)))
		do_unblock(&(barrier_table[id].block_queue));
	barrier_table[id].num_waiting=0;
	return 1;
}